package controllers

import (
	"github.com/astaxie/beego"
	"strconv"
	"goblog/models/dao"
	"goblog/wechat"
	"github.com/astaxie/beego/logs"
)

var Wechat *wechat.Wechat

func init() {
	Wechat = wechat.NewWechat()
	Wechat.AddHandler(string(wechat.MsgTypeText), &TextHandler{})
}

type TextHandler struct {
}
func (handler *TextHandler) Handle(msg wechat.MixMessage) wechat.Reply {
	return wechat.Reply{wechat.MsgTypeText, wechat.NewText(msg.Content)}
}

type MpEndpointController struct {
	beego.Controller
	mpConfigDao *dao.MpConfigDao
}

func (c *MpEndpointController) Get() {
	timestamp, nonce, sign := c.GetString("timestamp"), c.GetString("nonce"), c.GetString("signature")
	idVa := c.Ctx.Input.Param(":id")
	logs.Debug(c.Ctx.Request.Method)
	id, _ := strconv.Atoi(beego.Substr(idVa, 5, len(idVa)))
	config := c.getConfig(id)
	//将加密后获得的字符串与signature对比，如果一致，说明该请求来源于微信
	logs.Debug("get sign: ", sign)
	if wechat.Validate(config, sign, timestamp, nonce) {
		//如果请求来自于微信，则原样返回echostr参数内容 以上完成后，接入验证就会生效，开发者配置提交就会成功。
		echostr := c.GetString("echostr")
		c.Ctx.WriteString(echostr)

	} else {
		c.Ctx.WriteString("")
	}
}

func (c *MpEndpointController) Post() {
	logs.Info("公众号用户发文")
	if c.mpConfigDao == nil {
		c.mpConfigDao = new(dao.MpConfigDao)
	}
	timestamp, nonce, sign := c.GetString("timestamp"), c.GetString("nonce"), c.GetString("signature")
	idVa := c.Ctx.Input.Param(":id")
	id, _ := strconv.Atoi(beego.Substr(idVa, 5, len(idVa)))
	logs.Debug("post sign: ", sign)
	config := c.getConfig(id)
	reply := Wechat.Serve(config, c.Ctx.Input.RequestBody, sign, timestamp, nonce)
	c.Ctx.WriteString(reply)
}

func (c *MpEndpointController) getConfig(id int) wechat.MpConfig {
	if c.mpConfigDao == nil {
		c.mpConfigDao = new(dao.MpConfigDao)
	}
	mpConfig := c.mpConfigDao.Get(id);
	var config = wechat.MpConfig{};
	config.AppId = mpConfig.AppId
	config.Name = mpConfig.Name
	config.Salt = string(mpConfig.Salt)
	config.CertPass = mpConfig.CertPass
	config.CertPath = mpConfig.CertPath
	config.PartnerKey = mpConfig.PartnerKey
	config.PartnerId = mpConfig.PartnerId
	config.JsExpiresTime = mpConfig.JsExpiresTime
	config.JsApiTicket = mpConfig.JsApiTicket
	config.ExpiresTime = mpConfig.ExpiresTime
	config.AccessToken = mpConfig.AccessToken
	config.AesKey = mpConfig.AesKey
	config.Token = mpConfig.Token
	config.Secret = mpConfig.Secret
	return config
}
